import 'package:redux/redux.dart';
import '../models/follow_relation_entity.dart';
import '../data/default_follow_data.dart';

/// Redux关注状态
class ReduxFollowState {
  final List<FollowRelationEntity> followRelationCollection;

  const ReduxFollowState({this.followRelationCollection = const []});

  ReduxFollowState copyWith({
    List<FollowRelationEntity>? followRelationCollection,
  }) {
    return ReduxFollowState(
      followRelationCollection:
          followRelationCollection ?? this.followRelationCollection,
    );
  }
}

/// Redux关注动作
abstract class ReduxFollowAction {}

class InitializeFollowDataAction extends ReduxFollowAction {
  final List<FollowRelationEntity> followRelationList;
  InitializeFollowDataAction(this.followRelationList);
}

class AddFollowRelationAction extends ReduxFollowAction {
  final FollowRelationEntity newFollowRelation;
  AddFollowRelationAction(this.newFollowRelation);
}

class RemoveFollowRelationAction extends ReduxFollowAction {
  final String followerId;
  final String followingId;
  RemoveFollowRelationAction({
    required this.followerId,
    required this.followingId,
  });
}

/// Redux关注Reducer
ReduxFollowState followReducer(ReduxFollowState state, dynamic action) {
  if (action is InitializeFollowDataAction) {
    return state.copyWith(followRelationCollection: action.followRelationList);
  }

  if (action is AddFollowRelationAction) {
    final updatedRelations = List<FollowRelationEntity>.from(
      state.followRelationCollection,
    )..add(action.newFollowRelation);
    return state.copyWith(followRelationCollection: updatedRelations);
  }

  if (action is RemoveFollowRelationAction) {
    final updatedRelations =
        state.followRelationCollection.where((relation) {
          return !(relation.followerId == action.followerId &&
              relation.followingId == action.followingId);
        }).toList();
    return state.copyWith(followRelationCollection: updatedRelations);
  }

  return state;
}

/// Redux关注服务
class ReduxFollowManager {
  static final ReduxFollowManager _instance = ReduxFollowManager._internal();
  factory ReduxFollowManager() => _instance;
  ReduxFollowManager._internal();

  Store<dynamic>? _store;

  void initialize(Store<dynamic> store) {
    _store = store;
  }

  Store<dynamic> get store {
    if (_store == null) throw Exception('Follow service not initialized');
    return _store!;
  }

  void initializeFollowData() {
    final followData = List<FollowRelationEntity>.from(
      DefaultFollowDataCollection.defaultFollowRelationList,
    );
    store.dispatch(InitializeFollowDataAction(followData));
  }

  List<FollowRelationEntity> getAllFollowRelations() =>
      List.from(store.state.followState.followRelationCollection);

  List<String> getFollowingList(String userId) {
    final relations = store.state.followState.followRelationCollection;
    final result = <String>[];
    for (final relation in relations) {
      if (relation.followerId == userId) {
        result.add(relation.followingId);
      }
    }
    return result;
  }

  List<String> getFollowerList(String userId) {
    final relations = store.state.followState.followRelationCollection;
    final result = <String>[];
    for (final relation in relations) {
      if (relation.followingId == userId) {
        result.add(relation.followerId);
      }
    }
    return result;
  }

  bool isFollowing(String followerId, String followingId) {
    return store.state.followState.followRelationCollection.any(
      (relation) =>
          relation.followerId == followerId &&
          relation.followingId == followingId,
    );
  }

  int getFollowingCount(String userId) {
    return store.state.followState.followRelationCollection
        .where((relation) => relation.followerId == userId)
        .length;
  }

  int getFollowerCount(String userId) {
    return store.state.followState.followRelationCollection
        .where((relation) => relation.followingId == userId)
        .length;
  }

  Future<bool> followUser(String followerId, String followingId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));

      // 检查是否已经关注
      if (isFollowing(followerId, followingId)) {
        return false; // 已经关注了
      }

      final newRelation = FollowRelationEntity(
        relationId: 'follow_${DateTime.now().millisecondsSinceEpoch}',
        followerId: followerId,
        followingId: followingId,
        followTime: DateTime.now(),
      );

      store.dispatch(AddFollowRelationAction(newRelation));
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> unfollowUser(String followerId, String followingId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));

      // 检查是否已经关注
      if (!isFollowing(followerId, followingId)) {
        return false; // 没有关注关系
      }

      store.dispatch(
        RemoveFollowRelationAction(
          followerId: followerId,
          followingId: followingId,
        ),
      );
      return true;
    } catch (e) {
      return false;
    }
  }

  int getTotalFollowRelationCount() =>
      store.state.followState.followRelationCollection.length;
}
